package main

import (
	"fmt"
	"time"
)

func main() {
	//selectChanel()
	//selectChannelTimeout()
	channelTicker()
}

func channelTicker() {
	c := time.NewTicker(time.Second)
	for b := range c.C {
		fmt.Printf("time is %s\n", b)
	}
}

func selectChannelTimeout() {
	c1 := make(chan int, 1024)
	c2 := make(chan int, 1024)
	go func() {
		for a := 0; a < 10; a++ {
			time.Sleep(3 * time.Second)
			c1 <- a
			c2 <- a
		}
	}()
	for a := 0; a < 6; a++ {
		select {
		case i := <-c1:
			fmt.Printf("case1: %d \n", i)
		case i := <-c2:
			fmt.Printf("case2: %d \n", i)
		case <-time.After(time.Second):
			fmt.Println("timeout")
		}
	}
}

func selectChanel() {
	c1 := make(chan int, 1024)
	c2 := make(chan int, 1024)
	go func() {
		for a := 0; a < 10; a++ {
			c1 <- a
			c2 <- a
		}
	}()
	for a := 0; a < 6; a++ {
		select {
		case i := <-c1:
			fmt.Printf("case1: %d \n", i)
		case i := <-c2:
			fmt.Printf("case2: %d \n", i)
		default:
			fmt.Println("default")
		}
	}
}

func buffer() {
	// 无缓冲,无消费，发送端就会被阻塞，要想非阻塞可以加缓冲区
	c := make(chan int, 10)
	go func() {
		for a := 0; a < 6; a++ {
			c <- a
			fmt.Printf("send %d to channel\n", a)
			time.Sleep(time.Second)
		}
		fmt.Println("channel ready close")
		close(c)
	}()
	//go func() {
	//	for a := 0; a < 2; a++ {
	//		time.Sleep(2 * time.Second)
	//		i, flag := <-c
	//		fmt.Printf(" goruntine channel receive %d flag:%t\n", i, flag)
	//	}
	//}()

	for b := range c {
		fmt.Printf("main receive %d\n", b)
	}
	time.Sleep(6 * time.Second)
	fmt.Println("main function exit")
	// channel惊慌，一个线程里即发送又消费就死锁
	// channel 应该由发送者关闭，否则被关闭的channel无法接收消息
	// 消费close的channel时，不会被阻塞，第一个值为默认值，第二个返回值为false, 消费被close的channel会跳出循环
}
